"""
Author: Meng
Date: 2018/8/26
"""
from app.models.safety.sys_tasks_log import SysTasksLog
from app.models.task.task import SysTasks
import threading
import time
from settings import UPLOAD_PATH, PROJECT_ROOT
import os
import shutil

_clear_trash_file_name = 'clear_trash_file_executor'


def clear_files():
    from main import app

    with app.app_context():
        try:
            task = SysTasks.query_one(task_name=_clear_trash_file_name)
            print(task)

            if task:
                while True:

                    interval = task.interval if task.interval else 60 * 60 * 2
                    task = SysTasks.query_one(task_name=_clear_trash_file_name)
                    if task.status == 'stop':
                        SysTasksLog.create(task_name=_clear_trash_file_name, content='任务已结束',
                                           level='success')
                        return False
                    try:

                        all_del_paths = []
                        all_folder = os.listdir(UPLOAD_PATH)
                        for folder in all_folder:

                            user_path = os.path.join(UPLOAD_PATH, folder)
                            if os.path.isdir(user_path):
                                all_user_folder = os.listdir(user_path)
                                for item in all_user_folder:
                                    path = os.path.join(user_path, item)
                                    if os.path.isdir(path):
                                        all_del_paths.append(path)

                        for pa in all_del_paths:
                            shutil.rmtree(pa)
                        SysTasksLog.create(task_name=_clear_trash_file_name,
                                           content='删除文件数量: {}'.format(len(all_del_paths)),
                                           level='success')
                    except Exception as e:
                        SysTasksLog.create(task_name=_clear_trash_file_name, content='执行任务异常，code： {}'.format(str(e)),
                                           level='error')

                    time.sleep(interval)
            else:
                SysTasksLog.create(task_name=_clear_trash_file_name, content='未检索到任务名称，无法执行！', level='error')
        except Exception as e:
            print(e)
            SysTasksLog.create(task_name=_clear_trash_file_name, content='执行任务异常，code： {}'.format(str(e)),
                               level='error')

